<template>
  <div class="media-center">
    <el-container>
        <el-main class="leftMain">
          <div class="main-title">{{ $t('目录管理') }}</div>
            <Tree showMinType="1" @click="handleTreeClick" @refresh="handleTreeRefresh"></Tree>
        </el-main>
        <el-main class="rightMain">
          <el-tabs class="rightMain-tabs" style="height: 44px" v-model="activeName2">
            <el-tab-pane :label="$t('缩略图')" name="first"></el-tab-pane>
            <el-tab-pane :label="$t('详细信息')" name="second"></el-tab-pane>
          </el-tabs>
          <bs-main height="calc(100% - 44px)">
            <condition-row
              slot="header"
              :tabIndex="activeName2"
              @del="handCondition('del')"
              @action="(data) => handCondition('action', data)"
              @search="(data) => handCondition('search', data)"
              ></condition-row>
            <pagination
              slot="footer"
              :total="pageData.total"
              :page="pageData.current"
              :limit="pageData.size"
              :page-sizes="pageData.sizes"
              :showAllChecked="true" 
              :allChecked="allSize"
              @all="handleChangeAllSize"
              @pagination="doList"></pagination>
            
            <div style="height: 100%;">
              <div style="margin-left: -15px;" v-show="activeName2 === 'first'">
                <mini-panel
                  ref="miniPanel"
                  class="center"   
                  :datas="mediaData"
                  @dbClick="_openPreView" />
              </div>
              <list
                ref="list"
                class="center"
                height="calc( 100% - 15px )"
                v-show="activeName2 === 'second'"
                :list-data="mediaData"
                :has-select="false"
                :list-cols="listCols"
                :action-opts="actionOpts"
                :init-cols-props.sync="initColsProps"
                @sort="handleListSort"
                @cell-double-click="_openPreView">
                <template slot="auditStateSlot" slot-scope="{row}">
                  {{ row | getAuditStateName }}
                </template>
                <template slot="typeSlot" slot-scope="{row}">
                  {{ row.type | getTypeName }}
                </template>
                <template slot="actionSlot" slot-scope="{ row }">
                    <el-button @click.native="_openPreView(row)" size="mini" type="primary">预览</el-button>
                    <el-button @click.native="_openDownLoad(row)" size="mini" type="primary">下载</el-button>
                    <el-button @click.native="_handleDel(row)" size="mini" type="danger" v-has="'NEWS_MEDIA_DELETE'">删除</el-button>
                </template>
              </list>
            </div>
           
          </bs-main>
        </el-main>
    </el-container>
    <upload-dialog
      :visible.sync="uploadDialogShow"
      :init-folder-id="search.folderId"
      :init-user-id="searchUserId"
      @close="doList" />
    <preview-dialog :visible.sync="previewDialog.show" :pre-data="previewDialog.preData" />
  </div>
</template>

<script>
import Tree from '../components/NewsTree.vue'
import MiniPanel from '../../media/components/MiniPanel'
import List from '@/components/List'
import Pagination from '@/components/Pagination'
import ConditionRow from './components/ConditionRow'
import UploadDialog from './components/UploadDialog'
import PreviewDialog from '../../media/components/PreviewDialog'
import {fileTypeOpts, FILETYPE} from './const'
import NewsApi from '@/api/news'
import CommonApi from '@/api/common'
import {getFileSize} from '@/utils'

export default {
  filters: {
    getFileSize,
    getTypeName(v) {
      let fileType = fileTypeOpts.find(item => item.value == v)
      return fileType ? fileType.label : v
    },
    getAuditStateName(v) {
      let msg = ''
      if(v.auditState === 0) {
        // -1:待转码 -2:转码失败 -3:转码中
        switch(v.state) {
          case -1:
            msg = '待转码'
            break
          case -2:
            msg = '转码失败'
            break
          case -3:
            msg = '转码中'
            break
          default:
            msg = "不可用"
        }
        return msg
      } else {
        return v.auditState == '3' ? '可用' : '不可用'
      }
    }
  },
  components: {
    PreviewDialog,
    UploadDialog,
    Tree,
    MiniPanel,
    List,
    Pagination,
    ConditionRow
  },
  data() {

    const headerContextMenus = {
      width: '120px',
      items: [
        'sortUp',
        'sortDown',
        'line',
        'cols'
      ]
    }

    return {
      previewDialog: {
        show: false
      },
      activeName2: 'first',
      listCols: [
        {label: '名称', prop: 'name', headerContextMenus, minwidth: 80, showOverflowTooltip: true},
        {label: '大小', prop: 'fileSize', headerContextMenus, minwidth: 80},
        {label: '类型', prop: 'type', headerContextMenus, minwidth: 80, slot: true},
        // {label: '状态', prop: 'auditState', headerContextMenus, minwidth: 80, slot: true},
        {label: '宽', prop: 'width', headerContextMenus, minwidth: 80},
        {label: '高', prop: 'height', headerContextMenus, minwidth: 80},
        {label: '创建时间', prop: 'createdAt', headerContextMenus, minwidth: 100, showOverflowTooltip: true},
      ],
      sortFieldMap: {
        'name': 1,
        'fileSize': 2,
        'type': 3,
        'auditState': 4,
        'width': 5,
        'height': 6,
        'duration': 7,
        'refCount': 8,
        'validity': 11,
        'revision': 9,
        'createdAt': 10,
        'qrCode': 13
      },
      initColsProps: ['name', 'fileSize', 'type', 'auditState', 'width', 'height', 'createdAt'],
      search: {
        folderId: '0',
        queryType: 0,
        queryParam: ''
      },
      sort: {
        orders: '',
        sortField: ''
      },
      allSize: false,
      actionOpts: {
          show: true,
          align: 'center',
          width: '120px',
          hidEditBtn: true,
          hidDelBtn: true,
          name: '操作',
          slot: true,
      },
      mediaData:[],
      pageData: {
        page: 1,
        limit: 15,
        total: 0
      },
    }
  },
  computed:{
    searchUserId() {
      return ''
    },
    uploadDialogShow: {
      get() {
        return this.$store.state.media.isQuikUpload
      },
      set(val) {
        this.$store.dispatch('media/changeQuikUpload', {
          key: 'isQuikUpload',
          value: false
        })
      }
    }
  },
  mounted() {
      this.$nextTick(() => {
          this.doList({page:1})
      })
  },
  methods: {
    handleTreeClick(data) {
      this.search.folderId = data.id
      this.doList({page:1})
    },
    handleTreeRefresh() {
      this.search =  {
        folderId: '0',
        queryType: 0,
        queryParam: ''
      }
      this.doList({page:1})
    },
    handleDelClick(row) {
      this._handleDel(row)
    },
    handleSnapshotClick(row) {
      if(!row.snapshotPath) {
        this.$message.error('没有可以查看的快照')
        return
      }
      window.open(row.snapshotPath)
    },
    handleListSort({type, prop}) {
      if (this.sortFieldMap[prop]) {
        this.sort = {
          sortField: this.sortFieldMap[prop],
          orders: type.toLowerCase()
        }
        this.doList()
      }
    },
    getActiveItem() {
      if (this.activeName2 === 'first') {
        console.log(this.$refs.miniPanel.getActiveItem())
        return this.$refs.miniPanel.getActiveItem()
      } else {
        let items = this.$refs.list.getActiveItem()
        return items.length === 1 ? items[0] : items.length === 0 ? null : items
      }
    },
    handCondition(type, data) {
      switch(type) {
        case 'action':
          this._handleAction(data)
          break;
        case 'del':
          this._handleDel(
            this.getActiveItem()
          )
          break;
        case 'search':
          this._handleSearch(data)
          break;
        default: console.log('未知操作');
      }
    },
    _handleAction(type) {
      switch(type) {
        case '上传':
          this.$store.dispatch('media/changeQuikUpload', {
            key: 'isQuikUpload',
            value: true
          })
          break;
        case '下载':
          this._openDownLoad(
            this.getActiveItem()
          )
          break;
        case '预览':
          this._openPreView(
            this.getActiveItem()
          )
          break;
        default:
      }
    },
    _handleSearch({name, value}) {
      this.search = {
        ...this.search,
        queryParam: value,
        queryType: name
      }
      this.doList({ page:1 })
    },
    async _openDownLoad(file) {
      if (!file) {
        this.$alert('提示', '请先选择文件')
        return
      }
      if (file instanceof Array) {
        this.$alert('提示', '此操作不支持多选')
        return
      }
      const passFileType = [ // 能下载的文件
        FILETYPE.TEXT,
        FILETYPE.VIDEO,
        FILETYPE.AUDIO,
        FILETYPE.LOCAL_TEXT,
        FILETYPE.QRCODE,
        FILETYPE.PICTURE,
        FILETYPE.NET_PICTURE,
        FILETYPE.WEB_CAPTURE
      ]
      if (passFileType.indexOf(String(file.type)) === -1) return this.$alert('提示', '对不起，该媒体类型无法下载')
      if (file.path) {
        const previewTokenRes = file.path ? await CommonApi.previewToken({path: encodeURIComponent(file.path)}) : null
        var tempwindow=window.open('_blank');
        tempwindow.location.href = previewTokenRes ? previewTokenRes : file.path
      } else {
        this.$alert('提示', '对不起，未获取到文件地址，无法下载')
      }
    },
    async _openPreView(file) {
      if (!file) {
        this.$alert('提示', '请先选择文件')
        return
      }
      if (file instanceof Array) {
        this.$alert('提示', '此操作不支持多选')
        return
      }
      const passFileType = [ // 能预览的文件类型
        FILETYPE.VIDEO,
        FILETYPE.AUDIO,
        FILETYPE.TEXT,
        FILETYPE.LOCAL_TEXT,
        FILETYPE.QRCODE,
        FILETYPE.NET_PICTURE,
        FILETYPE.PICTURE,
        FILETYPE.WEB_CAPTURE
      ]
      // if (passFileType.indexOf(String(file.type)) === -1) return this.$alert('提示', '对不起，该媒体类型无法预览')
      // 重新获取url的token
      const previewTokenRes = file.path ? await CommonApi.previewToken({path: encodeURIComponent(file.path)}) : null
      const _isText = [FILETYPE.TEXT,FILETYPE.LOCAL_TEXT].some(i => i === String(file.type))
      const _isNET_PICTURE = String(file.type) === FILETYPE.NET_PICTURE
      if (_isText || _isNET_PICTURE) {
         // 获取文本文件内容
        const res = await NewsApi.getInfo({id: file.id}) 
        if(res) {
          let argus = res.argus ? JSON.parse(res.argus) : {}
          let attributes = argus.attributes
          if (attributes && typeof attributes === 'string') {
            attributes = JSON.parse(attributes)
          }
          this.previewDialog = {
            ...this.previewDialog,
            show: true,
            preData: {
              ...argus,
              ...file,
              ...res,
              ...attributes,
              showType: 3,
              _isText
            }
          }
          if(_isText) {
            const preContent = await NewsApi.getLocalInfo({path: previewTokenRes ? previewTokenRes : file.path})
            if(preContent) {
              this.previewDialog.preData.content = preContent
            }
          }
        }
      } else {
        this.previewDialog = {
          ...this.previewDialog,
          show: true,
          preData: {
            ...file,
            showType: 3,
            _isText: false
          }
        }
        if(previewTokenRes) {
          this.previewDialog.preData.path = previewTokenRes
        }
      }
    },
    async getInfo(id, cb) {
      const res = await NewsApi.getInfo({id})
      cb && cb(res)
    },
    async _handleDel(file) {
      if (!this.allSize && !file) {
        this.$alert('提示', '请先选择文件')
        return
      }
      let bool = false
      let queryData = {}
      if(!this.allSize) {
        let ids = []
        if (file instanceof Array) {
          file.forEach(item => {
            ids.push(item.id)
            if(item.refCount > 0) {
              bool = true
            }
          })
        }else{
          ids.push(file.id)
          if(file.refCount > 0) {
            bool = true
          }
        }
        if(bool) {
          this.$alert('提示', '选择的媒体已被使用,不能删除')
          return
        }
        const res = await this.$confirm('提示', '确定要删除吗？')
        if(res) {
            await NewsApi.deleteNewsMedia({ id: ids })
            this.$message.success('删除成功')
            this.allSize = false
            this.doList({page:1})
        }
      } else {
        queryData = {
          ...this.search,
          allSize: this.allSize,
        }
        const res = await this.$confirm('提示', '确定要删除吗？')
        if(res) {
            await NewsApi.deleteNewsMedia(queryData)
            this.$message.success('删除成功')
            this.allSize = false
            this.doList({page:1})
        }
      }
    },
    // 选择所有页
    handleChangeAllSize(val) {
      this.allSize = val
      this.$refs.list.clearSelection();
    },

    // 查询列表
    async doList(current) {
        if(current) {
            this.search = {
            ...this.search,
            ...current
            }
        }
        var queryData = this.search
        queryData.current = this.pageData.page
        queryData.size = this.pageData.limit
        const res = await NewsApi.newsMediaPage(queryData)
        if(res) {
            const records = res.records || []
            this.mediaData = records.map(item => {
              item.showType = 'newsMedia'
                return {
                  ...item,
                }
            })
            this.pageData.total = Number(res.total? res.total: 0)
        }
    },
    updateClickHandle() {

    },
    addClickHandle() {

    }
  }
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';
.mediaTree {
  width: 100%;
  .el-tabs--border-card {
    border: 0 !important;
  }
  ::v-deep .el-tabs--border-card .el-tabs__content {
    padding: 0;
  }
}
.mediaTree {
  // overflow-x: scroll;
  ::v-deep .el-tabs__item {
    padding: 0 !important;
    width: 125px;
    text-align: center;
  }
  ::v-deep .el-tabs__item:last-child {
    border-right: 0 !important;
  }
}

.media-center .rightMain .el-tabs {
  border-bottom: 0;
}
.media-center .rightMain .el-tabs__content {
  padding: 0;
}
.el-tabs--border-card{border: 0 !important;}
.el-button-group .el-button--primary:last-child {
  height: 32px;
}
.el-button-group .el-button--primary:first-child {
    height: 30px;
}
</style>